import axios, { ResponseType, AxiosResponse, CancelToken } from 'axios'
import qs from 'qs'

interface RequestDataInfo {
  url: string
  headers?: any
  param?: any
  data?: any
  timeout?: number
  responseType?: ResponseType
  // 是否返回全部信息
  shouldResponseAll?: boolean
  // 是否为第三方接口
  isThirdPartyUrl?: boolean
  onUploadProgress?: any
  cancelToken?: CancelToken,
  encryption?: boolean
}

function wrapUrl(url: string) {
  return url
}
// 允许携带cookie
axios.defaults.withCredentials = true

axios.interceptors.request.use((config) => {
  if (config.method === 'get') {
    config.paramsSerializer = (params: any) => {
      return qs.stringify(params, { arrayFormat: 'repeat' })
    }
  }
  return config
})

export const requestInterceptor = axios.interceptors
export const request = axios
export async function requestGet(resData: RequestDataInfo): Promise<any> {
  const {
    url = '',
    headers = {},
    param = {},
    data = {},
    timeout = 60000,
    responseType = 'json',
    shouldResponseAll = false,
    cancelToken = null,
  } = resData
  return await axios({
    url: wrapUrl(url),
    method: 'GET',
    headers,
    params: param,
    data: data,
    responseType,
    timeout,
    cancelToken,
  }).then((res: AxiosResponse) => (shouldResponseAll ? res : res?.data))
}

// post请求
export async function requestPost(resData: RequestDataInfo): Promise<any> {
  const {
    url = '',
    headers = {},
    data = {},
    param = {},
    timeout = 60000,
    responseType = 'json',
    shouldResponseAll = false,
    onUploadProgress = null,
    cancelToken = null,
  } = resData
  let newData: any = data

  return await axios({
    url: wrapUrl(url),
    method: 'POST',
    headers:  headers,
    params: param,
    data: newData,
    responseType: responseType,
    timeout,
    onUploadProgress,
    cancelToken,
  }).then((res: AxiosResponse) => {
    return shouldResponseAll ? res : res.data
  })
}

// put请求
export async function requestPut(resData: RequestDataInfo): Promise<any> {
  const {
    url = '',
    headers = {},
    data = {},
    param = {},
    timeout = 60000,
    responseType = 'json',
    shouldResponseAll = false,
    cancelToken = null,
  } = resData
  return await axios({
    url: wrapUrl(url),
    method: 'PUT',
    headers,
    params: param,
    data: data,
    responseType,
    timeout,
    cancelToken,
  }).then((res: AxiosResponse) => (shouldResponseAll ? res : res?.data))
}

// delete请求
export async function requestDelete(resData: RequestDataInfo): Promise<any> {
  const {
    url = '',
    headers = {},
    data = {},
    param = {},
    timeout = 60000,
    responseType = 'json',
    shouldResponseAll = false,
    cancelToken = null,
  } = resData
  return await axios({
    url: wrapUrl(url),
    method: 'DELETE',
    headers,
    params: param,
    data: data,
    responseType,
    timeout,
    cancelToken,
  }).then((res: AxiosResponse) => (shouldResponseAll ? res : res?.data))
}
